from django.views import View
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from .models import User, Address, get_db
import json


class BaseView(View):
    """基类视图，包含数据库会话获取逻辑"""

    def get_db_session(self):
        """获取数据库会话"""
        return next(get_db())

    def custom_serialize(self, table_obj):
        # 转化 User 对象为字典，过滤掉 SQLAlchemy 的内部字段
        table_obj_dict = table_obj.__dict__.copy()  # 复制一份字典
        table_obj_dict.pop('_sa_instance_state', None)  # 移除 _sa_instance_state 字段
        return table_obj_dict


@method_decorator(csrf_exempt, name='dispatch')
class UserView(BaseView):
    # 列出所有 User（GET）
    def get(self, request, *args, **kwargs):
        db = self.get_db_session()  # 获取数据库会话
        # 如果传递了 'pk' 参数（即获取单个用户）
        pk = kwargs.get('pk', None)

        if pk is not None:
            # 获取单个用户
            user = db.query(User).filter(User.id == pk).first()
            if user is None:
                return JsonResponse([], safe=False, status=404)
            return JsonResponse(self.custom_serialize(user), status=200)

        users = db.query(User).all()
        return JsonResponse([self.custom_serialize(user) for user in users], safe=False, status=200)

    # 创建 User（POST）
    def post(self, request, *args, **kwargs):
        name = request.POST.get('name')
        fullname = request.POST.get('fullname')
        if name and fullname:
            db = self.get_db_session()
            user = User(name=name, fullname=fullname)
            db.add(user)
            db.commit()
            return JsonResponse({'id': user.id, 'name': user.name, 'fullname': user.fullname}, status=201)

        return JsonResponse({'error': 'Name and fullname are required'}, status=400)

    # 更新 User（PUT）
    def put(self, request, pk, *args, **kwargs):
        db = self.get_db_session()
        user = db.query(User).filter(User.id == pk).first()
        data = json.loads(request.body)
        if user:
            data = json.loads(request.body)
            user.name = data.get('name', user.name)
            user.fullname = data.get('fullname', user.fullname)
            
            db.commit()
            return JsonResponse({'id': user.id, 'name': user.name, 'fullname': user.fullname}, status=200)
        return JsonResponse({'error': 'User not found'}, status=404)

    # 删除 User（DELETE）
    def delete(self, request, pk, *args, **kwargs):
        db = self.get_db_session()
        user = db.query(User).filter(User.id == pk).first()
        if user:
            db.delete(user)
            db.commit()
            return JsonResponse({'message': 'User deleted successfully'}, status=200)
        return JsonResponse({'error': 'User not found'}, status=404)


@method_decorator(csrf_exempt, name='dispatch')
class AddressView(BaseView):
    # 列出所有 Address（GET）
    def get(self, request, *args, **kwargs):
        db = self.get_db_session()  # 获取数据库会话
        # 如果传递了 'pk' 参数（即获取单个用户）
        pk = kwargs.get('pk', None)

        if pk is not None:
            # 获取单个用户
            address = db.query(Address).filter(Address.id == pk).first()
            if address is None:
                return JsonResponse([], safe=False, status=404)
            return JsonResponse(self.custom_serialize(address), status=200)

        addresses = db.query(Address).all()
        return JsonResponse([self.custom_serialize(address) for address in addresses], safe=False, status=200)

    # 创建 Address（POST）
    def post(self, request, *args, **kwargs):
        db = self.get_db_session()
        email_address = request.POST.get('email_address')
        user_id = request.POST.get('user_id')
        user = db.query(User).filter(User.id == user_id).first()
        if email_address and user:
            address = Address(email_address=email_address, user_id=user.id)
            db.add(address)
            db.commit()
            return JsonResponse(
                {'id': address.id, 'email_address': address.email_address, 'user_id': address.user_id},
                status=201
            )

        return JsonResponse({'error': 'email_address and a valid user_id are required'}, status=400)

    # 更新 Address（PUT）
    def put(self, request, pk, *args, **kwargs):
        db = self.get_db_session()
        address = db.query(Address).filter(Address.id == pk).first()
        if address:
            data = json.loads(request.body)
            user = db.query(User).filter(User.id == data.get('user_id', address.user_id)).first()
            if user is None:
                return JsonResponse({'error': 'User not found'}, status=404)
            address.user_id = user.id
            address.email_address = data.get('email_address', address.email_address)

            db.commit()
            return JsonResponse(
                {'id': address.id, 'email_address': address.email_address, 'user_id': address.user_id},
                status=200
            )
        return JsonResponse({'error': 'Address not found'}, status=404)

    # 删除 Address（DELETE）
    def delete(self, request, pk, *args, **kwargs):
        db = self.get_db_session()
        address = db.query(Address).filter(Address.id == pk).first()
        if address:
            db.delete(address)
            db.commit()
            return JsonResponse({'message': 'Address deleted successfully'}, status=200)
        return JsonResponse({'error': 'Address not found'}, status=404)

